import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import './index.scss'
import { useDispatch } from 'react-redux'
import { fetchLogin } from '@/store/modules/user'
import { useNavigate } from 'react-router-dom'
import { useEffect, useState } from 'react'

const Login = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()

  const [ userPhone, setUserPhone ] = useState('')
  const [ userPassword, setUserPassword ] = useState('')
  const [ isChecked, setChecked ] = useState(false)

  // 记住我:自动回填手机号、密码
  const onRemember = (value) => {
    const checked = value.target.checked
    setChecked(checked)
  }

  const onFinish = async (values) =>{
    // console.log(values);
    // 触发异步action 手机号：13800000002 验证码：246810
    await dispatch(fetchLogin(values))
    // 保存用户信息
    if(isChecked){
      localStorage.setItem('mobile', userPhone)
      localStorage.setItem('code', userPassword)
    }
    // 跳转到目标路径
    navigate('/')
    message.success('登录成功')
  }

  const [ form ] = Form.useForm()
  useEffect(() => {

    const saveUserPhone = localStorage.getItem('mobile')
    const saveUserCode = localStorage.getItem('code')

    function getUserInfo(){
      setUserPhone(saveUserPhone)
      setUserPassword(saveUserCode)
      console.log(saveUserPhone);
      
      form.setFieldsValue({
        mobile: saveUserPhone,
        code: saveUserCode
      })
    }
    if(saveUserPhone){
      getUserInfo()
    }
    
  }, [form, isChecked])
  return(
    <div className="login">
      <Card className='login-container' title="极客园">
          <Form validateTrigger="onBlur" onFinish={onFinish} form={form}>
            <Form.Item 
              name="mobile"
              // 多条校验逻辑，顺序校验
              rules={[
                { 
                  required: true,
                  message: '请输入你的手机号!' 
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的手机号格式!'
                }
              ]}>
              <Input size='large' placeholder='请输入手机号' onChange={(e) => setUserPhone(e.target.value)}></Input> 
            </Form.Item>
            <Form.Item  
              name="code"
              rules={[
                {
                  required: true,
                  message: '请输入你的验证码!',
                },
              ]}>
              <Input size='large' placeholder='请输入验证码' onChange={(e) => setUserPassword(e.target.value)}></Input>
            </Form.Item>
            <Form.Item>
              <Checkbox className='login-from-remember' checked={isChecked} onChange={onRemember}>记住我</Checkbox>
            </Form.Item>
            <Form.Item>
              <Button type='primary' htmlType='submit' size='large' block>
                登录
              </Button>
            </Form.Item>
          </Form>
      </Card>
    </div>
  )
}

export default Login